#       ChallengeManager.py
#       
#       Copyright 2008 Joshua Scotton <josh@joshuascotton.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2008, Joshua Scotton"
__author__ = "Joshua Scotton <josh@joshuascotton.com>"
__version__ = 0.1

import os
import sys
import wx

from Challenge import Challenge, Entry, Item

#Menu IDs next is 001111
ID_NEW = 001101
ID_OPEN = 000000
ID_EDIT_CHALLENGE = 000001
ID_SHOW_XML = 001110
ID_SAVE = 000010
ID_EXIT = 000011
ID_LOAD_FILES = 000100
ID_UPLOAD_SERVER = 000101
ID_UPLOAD_GALLERY = 000110
ID_GET_ENTRY_CODE = 000111
ID_GET_VOTING_CODE = 001000
ID_BLOG_ENTRY = 001001
ID_BLOG_VOTING = 001010
ID_BLOG_RESULTS = 001011
ID_ABOUT = 001100
   
class ChallengeManager:
    
    def __init__(self, file=""):
        """
        Starts it all off
        """
        self.challenge = None
        self.app = wx.PySimpleApp()
        self.frame = CHMainWindow(self, None, -1, "ChallengeHelper " + str(__version__))
        self.app.MainLoop()   
    
    def OnNew(self, e):
        #TODO ask if you want to save previous challenge
        #ie if not self.challenge == None:
        #       message(do you want to save)
        self.challenge = Challenge()
        dialog = wx.FileDialog(self.frame, "Create a challenge XML file", os.path.abspath('.'), "", "*.xml", wx.SAVE)
        if dialog.ShowModal() == wx.ID_OK:
            filename=dialog.GetFilename()
            dirname=dialog.GetDirectory()
            self.challenge.setFile(os.path.join(dirname, filename))
            self.challenge.save()
            self.challenge.load()
            self.refresh()
        dialog.Destroy()
        
    def OnOpen(self, e):
        #TODO ask if you want to save previous challenge
        #ie if not self.challenge == None:
        #       message(do you want to save)
        self.challenge = Challenge()
        dialog = wx.FileDialog(self.frame, "Choose a challenge XML file", os.path.abspath('.'), "", "*.xml", wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            filename=dialog.GetFilename()
            dirname=dialog.GetDirectory()
            self.challenge.setFile(os.path.join(dirname, filename))
            self.challenge.load()
            self.refresh()
        dialog.Destroy()
    def OnEditChallenge(self, e):
        pass
    def OnSave(self, e):
        self.challenge.save()
    def OnExit(self, e):
        #TODO ask if they want to save
        self.frame.Close(True)
    def OnShowXML(self, e):
        #TODO do better gui for this
        print self.challenge.toXML()
    def OnLoadFiles(self, e):
        dialog = wx.DirDialog(self.frame, "Choose the Challenge Folder", style=1, defaultPath=os.path.abspath('.'))
        if dialog.ShowModal() == wx.ID_OK:
            dirname=dialog.GetPath()
            self.loadItems(dirname)
            self.refresh()
        dialog.Destroy()
    def OnUploadServer(self, e):
        pass
    def OnUploadGallery(self, e):
        pass
    def OnGetEntryCode(self, e):
        pass
    def OnGetVotingCode(self, e):
        pass
    def OnBlogEntry(self, e):
        pass
    def OnBlogVoting(self, e):
        pass
    def OnBlogResults(self, e):
        pass
    def OnAbout(self, e):
        pass
    def loadItems(self, folder):
        filenames = [filename for filename in os.listdir(folder) if filename.endswith(".jpg")] 
        for fname in filenames:
            print "Resizing " + fname + " ..."
            #copy and rename the file, then resize it 
            os.system("cp \""+ os.path.join(folder, fname) +"\" \""+ os.path.join(folder, "thumb-"+fname) + "\"")
            os.system("mogrify -resize \">150\" \""+ os.path.join(folder, "thumb-"+fname) +"\"")
            self.challenge.addEntryItem("Unknown", os.path.join(folder, fname), 0)
        
    def refresh(self):
        
        while self.frame.GetSizer().Remove(0):
            self.frame.Layout()
        
        for entry in self.challenge.getEntries():
            miniSizer = wx.BoxSizer(wx.VERTICAL)
            miniSizer.Add(wx.Button(self.frame, wx.ID_ANY, entry.artist),1,wx.EXPAND)
            for item in entry.getItems():
                (folder, fname) = os.path.split(item.filename)
                imageFile = os.path.join(folder, "thumb-"+fname)
                image = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                button = wx.BitmapButton(self.frame, wx.ID_ANY, image)
                miniSizer.Add(button,1,wx.EXPAND)
                
            self.frame.GetSizer().Add(miniSizer,1,wx.EXPAND)
        
        self.frame.Layout()
        self.frame.Refresh()

class CHMainWindow(wx.Frame):
    
    def __init__(self, manager, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400,300))
        
        self.manager = manager
        self.sizer=wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(wx.Button(self, wx.ID_ANY, "Button 1"),1,wx.EXPAND)
        self.sizer.Add(wx.Button(self, wx.ID_ANY, "Button 2"),1,wx.EXPAND)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        #self.sizer.Fit(self)
        
        #Add Menu Bar
        self.SetMenuBar(CHMenuBar())
        self.CreateStatusBar()
        
        #Setup Action Menu Links and then loop through them adding to EVT_MENU
        menu_dict = {
            ID_NEW : self.manager.OnNew,
            ID_OPEN : self.manager.OnOpen,
            ID_EDIT_CHALLENGE : self.manager.OnEditChallenge,
            ID_SHOW_XML : self.manager.OnShowXML,
            ID_SAVE : self.manager.OnSave,
            ID_EXIT : self.manager.OnExit,
            ID_LOAD_FILES : self.manager.OnLoadFiles,
            ID_UPLOAD_SERVER : self.manager.OnUploadServer,
            ID_UPLOAD_GALLERY : self.manager.OnUploadGallery,
            ID_GET_ENTRY_CODE : self.manager.OnGetEntryCode,
            ID_GET_VOTING_CODE : self.manager.OnGetVotingCode,
            ID_BLOG_ENTRY : self.manager.OnBlogEntry,
            ID_BLOG_VOTING : self.manager.OnBlogVoting,
            ID_BLOG_RESULTS : self.manager.OnBlogResults,
            ID_ABOUT : self.manager.OnAbout
        }
        for key in menu_dict:
            wx.EVT_MENU(self, key, menu_dict[key])
                
        self.Show(True)

class CHMenuBar(wx.MenuBar):
    def __init__(self):
        wx.MenuBar.__init__(self)
        #&Challenge
        #   &New
        #   &Open
        #   &Edit
        #   Show &XML
        #   &Save
        #   E&xit
        #&Admin
        #   &Load Files
        #   Upload Files to &Server
        #   Upload Files to &Gallery
        #   Get E&ntry BBCode
        #   Get V&oting BBCode
        #   Blog &Entry Notice
        #   Blog &Voting Notice
        #   Blog &Results Notice
        #&Help
        #   A&bout
        chamenu = wx.Menu()
        admmenu = wx.Menu()
        hlpmenu = wx.Menu()
        
        chamenu.Append(ID_NEW,"&New"," New Challenge")
        chamenu.Append(ID_OPEN,"&Open"," Open Challenge")
        chamenu.Append(ID_EDIT_CHALLENGE,"&Edit"," Edit Challenge")
        chamenu.Append(ID_SHOW_XML,"Show &XML"," Show Challenge XML")
        chamenu.Append(ID_SAVE,"&Save"," Save Challenge")
        chamenu.AppendSeparator()
        chamenu.Append(ID_EXIT,"E&xit"," Exit")
        
        admmenu.Append(ID_LOAD_FILES,"&Load Files"," Load files from file")
        admmenu.AppendSeparator()
        admmenu.Append(ID_UPLOAD_SERVER,"Upload Files to &Server"," Upload entry files to the server")
        admmenu.Append(ID_UPLOAD_GALLERY,"Upload Files to &Gallery"," Upload entry pictures to the gallery")
        admmenu.AppendSeparator()
        admmenu.Append(ID_GET_ENTRY_CODE,"Get E&ntry BBCode"," Get bbcode for the entries thread")
        admmenu.Append(ID_GET_VOTING_CODE,"Get V&oting BBCode"," Get bbcode for the voting thread")
        admmenu.AppendSeparator()
        admmenu.Append(ID_BLOG_ENTRY,"Blog &Entry Notice","  Post a blog entry about the challenge entries thread")
        admmenu.Append(ID_BLOG_VOTING,"Blog &Voting Notice","  Post a blog entry about the challenge voting thread")
        admmenu.Append(ID_BLOG_RESULTS,"Blog &Results Notice"," Post a blog entry about the challenge results")
        
        hlpmenu.Append(ID_ABOUT, "A&bout"," About ChallengeHelper " + str(__version__))
        
        self.Append(chamenu,"&Challenge")
        self.Append(admmenu,"&Admin")
        self.Append(hlpmenu,"&Help")
    
if __name__ == '__main__':
    manager = ChallengeManager()
    
